<?php
namespace App\GraphQL\Mutations\PriceSpecification;

use App\Models\PriceSpecification;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

class Create
{

    /**
     * Return a value for the field.
     *
     * @param null $rootValue
     *            Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param mixed[] $args
     *            The arguments that were passed into the field.
     * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context
     *            Arbitrary data that is shared between all fields of a single query.
     * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo
     *            Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $data = $args['input'];
        $authUser = auth()->user();
        $data['user_id']=$authUser->id;
        $this->validate($data);
        // 创建价格
        
        $data['price'] = intval($data['price']*100);
        PriceSpecification::create($data);
        return [
            'status' => '200',
            'message' => '创建成功'
        ];
    }

    public function validate($data)
    {
        $cates = [
            'NORMAL',
            'PRIVATE'
        ];
        $styles = [
            'INTERNET_CAFE',
            'TEA_HOUSE'
        ];
        $rules = [
            'name' => [
                'required',
                'max:18'
            ],
            'cate' => [
                'required',
                Rule::in($cates)
            ],
            'style'=>[
                'required',
                Rule::in($styles)
            ],
            'duration'=>[
                'required',
                'numeric'
            ],
            'price' => [
                'required',
                'numeric',
            ]
        ];
        if($data['cate'] === 'PRIVATE') {
            $rules['province']=[
                'required'
            ];
        }
        $messages = [
            'name.required' => '名称不能为空',
            'name.max' => '名称不能超过18个字',
            'cate.required' => '分类不能为空',
            'cate.in' => '分类不能超出限制',
            'style.required' => '款式不能为空',
            'style.in' => '款式不能超出限制',
            'duration.required' => '时长不能为空',
            'duration.numeric' => '时长为数字',
            'price.required' => '价格不能为空',
            'price.numeric' => '价格为数字',
            'province.required'=>'地区不能为空'
        ];
        $validate = Validator::make($data, $rules, $messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        return true;
    }
}
